<!-- frontend/src/pages/MedicalAnalysis.vue -->
<template>
  <div class="medical-analysis">
    <!-- 导航栏 -->
    <div class="nav-header">
      <button class="btn secondary" @click="$router.push('/chat')">
        ← 返回聊天
      </button>
      <h1>🏥 Med-DistillFL医学影像分析系统</h1>
    </div>

    <div class="analysis-layout">
      <!-- 左侧：患者信息和图像上传 -->
      <div class="left-panel">
        <!-- 患者信息区 -->
        <div class="patient-info-section">
          <h3>📝 患者基本信息</h3>
          <div class="patient-form">
            <div class="form-row">
              <div class="form-group">
                <label>姓名</label>
                <input v-model="patientInfo.name" type="text" placeholder="请输入患者姓名">
              </div>
              <div class="form-group">
                <label>年龄</label>
                <input v-model="patientInfo.age" type="text" placeholder="请输入年龄">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>性别</label>
                <select v-model="patientInfo.gender">
                  <option value="">请选择</option>
                  <option value="男">男</option>
                  <option value="女">女</option>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label>病史摘要</label>
              <textarea v-model="patientInfo.history" rows="3" placeholder="请输入病史信息"></textarea>
            </div>
            <button class="btn primary" @click="updatePatientInfo" :disabled="updating">
              {{ updating ? '保存中...' : '保存患者信息' }}
            </button>
          </div>
        </div>

        <!-- 图像上传区 -->
        <div class="image-upload-section">
          <h3>📷 上传医学影像</h3>
          <div class="upload-area" :class="{ 'drag-over': dragOver }" 
               @drop="handleDrop" 
               @dragover.prevent="dragOver = true"
               @dragleave="dragOver = false"
               @click="triggerFileInput">
            <input ref="fileInput" type="file" accept="image/*" @change="handleFileSelect" style="display: none;">
            <div v-if="!selectedImage" class="upload-placeholder">
              <div class="upload-icon">📁</div>
              <p>点击或拖拽上传医学影像</p>
              <p class="upload-hint">支持 JPG, PNG, DICOM 等格式</p>
            </div>
            <div v-else class="image-preview">
              <img :src="imagePreviewUrl" alt="医学影像预览">
              <button class="remove-image" @click.stop="removeImage">✕</button>
            </div>
          </div>
          
          <!-- 自定义分析指令 -->
          <div class="custom-prompt">
            <label>自定义分析指令（可选）</label>
            <textarea v-model="customPrompt" rows="3" 
                      placeholder="输入特定的分析要求，如关注某个部位或症状..."></textarea>
          </div>
          
          <button class="btn primary analyze-btn" 
                  @click="analyzeImage" 
                  :disabled="!selectedImage || analyzing">
            {{ analyzing ? '分析中...' : '开始分析' }}
          </button>
        </div>
      </div>

      <!-- 右侧：分析结果和报告 -->
      <div class="right-panel">
        <!-- 分析结果显示区 -->
        <div class="analysis-results">
          <h3>🔍 分析结果</h3>
          <div v-if="analyzing" class="loading">
            <div class="spinner"></div>
            <p>AI正在分析医学影像，请稍候...</p>
          </div>
          <div v-else-if="analysisResult" class="result-content">
            <div class="result-header">
              <span class="timestamp">{{ formatTime(analysisResult.timestamp) }}</span>
              <button class="btn ghost" @click="copyResult">复制结果</button>
            </div>
            <div class="markdown-content" v-html="renderMarkdown(analysisResult.analysis_result)"></div>
          </div>
          <div v-else class="no-result">
            <p>请上传医学影像并开始分析</p>
          </div>
        </div>

        <!-- 报告生成区 -->
        <div class="report-section">
          <h3>📋 诊疗报告</h3>
          <div class="report-actions">
            <button class="btn primary" @click="generateReport" :disabled="!analysisResult || generatingReport">
              {{ generatingReport ? '生成中...' : '生成诊疗报告' }}
            </button>
            <button class="btn secondary" @click="downloadReport" :disabled="!medicalReport">
              下载报告
            </button>
          </div>
          <div v-if="medicalReport" class="report-content">
            <div class="markdown-content" v-html="renderMarkdown(medicalReport)"></div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { API_BASE_URL } from '@/config/api';

const router = useRouter();

// 响应式数据
const patientInfo = reactive({
  name: '',
  age: '',
  gender: '',
  history: ''
});

const selectedImage = ref<File | null>(null);
const imagePreviewUrl = ref<string>('');
const customPrompt = ref('');
const dragOver = ref(false);
const analyzing = ref(false);
const updating = ref(false);
const generatingReport = ref(false);
const analysisResult = ref<any>(null);
const medicalReport = ref<string>('');
const fileInput = ref<HTMLInputElement>();

// 上传图像相关方法
const triggerFileInput = () => {
  fileInput.value?.click();
};

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    setSelectedImage(file);
  }
};

const handleDrop = (event: DragEvent) => {
  event.preventDefault();
  dragOver.value = false;
  const file = event.dataTransfer?.files[0];
  if (file && file.type.startsWith('image/')) {
    setSelectedImage(file);
  }
};

const setSelectedImage = (file: File) => {
  selectedImage.value = file;
  const reader = new FileReader();
  reader.onload = (e) => {
    imagePreviewUrl.value = e.target?.result as string;
  };
  reader.readAsDataURL(file);
};

const removeImage = () => {
  selectedImage.value = null;
  imagePreviewUrl.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

// API调用方法
const updatePatientInfo = async () => {
  updating.value = true;
  try {
    const response = await fetch(`${API_BASE_URL}/api/medical/update-patient`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(patientInfo)
    });
    
    const result = await response.json();
    if (result.success) {
      alert('患者信息已保存');
    } else {
      alert('保存失败：' + result.error);
    }
  } catch (error) {
    alert('保存失败：' + error);
  } finally {
    updating.value = false;
  }
};

const analyzeImage = async () => {
  if (!selectedImage.value) return;
  
  analyzing.value = true;
  try {
    // 1. 先上传图像
    const formData = new FormData();
    formData.append('file', selectedImage.value);
    
    const uploadResponse = await fetch(`${API_BASE_URL}/api/medical/upload-image`, {
      method: 'POST',
      body: formData
    });
    
    const uploadResult = await uploadResponse.json();
    if (!uploadResult.success) {
      throw new Error(uploadResult.error);
    }
    
    // 2. 分析图像
    const analyzeResponse = await fetch(`${API_BASE_URL}/api/medical/analyze`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        image_path: uploadResult.file_path,
        custom_prompt: customPrompt.value || null
      })
    });
    
    const analyzeResult = await analyzeResponse.json();
    if (analyzeResult.success) {
      analysisResult.value = analyzeResult;
    } else {
      throw new Error(analyzeResult.error);
    }
    
  } catch (error) {
    alert('分析失败：' + error);
  } finally {
    analyzing.value = false;
  }
};

const generateReport = async () => {
  if (!analysisResult.value) return;
  
  generatingReport.value = true;
  try {
    const response = await fetch(`${API_BASE_URL}/api/medical/generate-report`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        analysis_history: [analysisResult.value]
      })
    });
    
    const result = await response.json();
    if (result.success) {
      medicalReport.value = result.report;
    } else {
      throw new Error(result.error);
    }
    
  } catch (error) {
    alert('报告生成失败：' + error);
  } finally {
    generatingReport.value = false;
  }
};

const downloadReport = () => {
  if (!medicalReport.value) return;
  
  const blob = new Blob([medicalReport.value], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `${patientInfo.name || '患者'}_诊疗报告_${new Date().toISOString().split('T')[0]}.txt`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const copyResult = () => {
  if (analysisResult.value?.analysis_result) {
    navigator.clipboard.writeText(analysisResult.value.analysis_result);
    alert('结果已复制到剪贴板');
  }
};

// 工具方法
const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN');
};

const renderMarkdown = (content: string) => {
  // 简单的markdown渲染，处理基本格式
  return content
    .replace(/## (.*)/g, '<h2>$1</h2>')
    .replace(/### (.*)/g, '<h3>$1</h3>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/- (.*)/g, '<li>$1</li>')
    .replace(/\n/g, '<br>')
    .replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');
};
</script>

<style scoped>
.medical-analysis {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--background, #f5f5f5);
  --background: #f5f5f5;
  --card: #ffffff;
  --border: #e6eaf2;
  --foreground: #0f172a;
  --muted-foreground: #64748b;
  --primary: #2b6cff;
  --primary-foreground: #ffffff;
  --secondary: #f1f5f9;
  --secondary-foreground: #0f172a;
  --muted: #f7f9fd;
}

.nav-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border);
  background: var(--card);
}

.nav-header h1 {
  margin: 0;
  font-size: 1.5rem;
  color: var(--primary);
}

.analysis-layout {
  flex: 1;
  display: grid;
  grid-template-columns: 400px 1fr;
  gap: 24px;
  padding: 24px;
  overflow: hidden;
}

.left-panel, .right-panel {
  display: flex;
  flex-direction: column;
  gap: 24px;
  overflow-y: auto;
}

/* 患者信息区 */
.patient-info-section {
  background: var(--card);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--border);
}

.patient-info-section h3 {
  margin: 0 0 16px 0;
  color: var(--foreground);
}

.form-row {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--foreground);
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid var(--border);
  border-radius: 8px;
  background: var(--background);
  color: var(--foreground);
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
  min-height: 80px;
}

/* 图像上传区 */
.image-upload-section {
  background: var(--card);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--border);
}

.image-upload-section h3 {
  margin: 0 0 16px 0;
  color: var(--foreground);
}

.upload-area {
  border: 2px dashed var(--border);
  border-radius: 12px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.upload-area:hover,
.upload-area.drag-over {
  border-color: var(--primary);
  background: var(--primary-foreground);
}

.upload-placeholder .upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.upload-placeholder p {
  margin: 8px 0;
  color: var(--foreground);
}

.upload-hint {
  font-size: 12px;
  color: var(--muted-foreground);
}

.image-preview {
  position: relative;
}

.image-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 8px;
}

.remove-image {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  border: none;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.custom-prompt {
  margin-bottom: 16px;
}

.custom-prompt label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--foreground);
}

.custom-prompt textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid var(--border);
  border-radius: 8px;
  background: #ffffff !important;
  color: #0f172a !important;
  font-size: 14px;
  resize: vertical;
}

.analyze-btn {
  width: 100%;
}

/* 分析结果区 */
.analysis-results {
  background: var(--card);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--border);
  flex: 1;
}

.analysis-results h3 {
  margin: 0 0 16px 0;
  color: var(--foreground);
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid var(--border);
  border-top: 4px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.result-content {
  max-height: 500px;
  overflow-y: auto;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--border);
}

.timestamp {
  font-size: 12px;
  color: var(--muted-foreground);
}

.no-result {
  text-align: center;
  padding: 40px;
  color: var(--muted-foreground);
}

/* 报告区 */
.report-section {
  background: var(--card);
  border-radius: 12px;
  padding: 20px;
  border: 1px solid var(--border);
}

.report-section h3 {
  margin: 0 0 16px 0;
  color: var(--foreground);
}

.report-actions {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.report-content {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid var(--border);
  border-radius: 8px;
  padding: 16px;
  background: var(--background);
}

/* Markdown内容样式 */
.markdown-content {
  line-height: 1.6;
  color: var(--foreground);
}

.markdown-content h2 {
  color: var(--primary);
  border-bottom: 1px solid var(--border);
  padding-bottom: 8px;
  margin: 24px 0 16px 0;
}

.markdown-content h3 {
  color: var(--foreground);
  margin: 20px 0 12px 0;
}

.markdown-content ul {
  margin: 12px 0;
  padding-left: 24px;
}

.markdown-content li {
  margin: 8px 0;
}

.markdown-content strong {
  color: var(--primary);
}

/* 按钮样式 */
.btn {
  padding: 12px 24px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.btn.primary {
  background: var(--primary);
  color: var(--primary-foreground);
}

.btn.primary:hover:not(:disabled) {
  opacity: 0.9;
}

.btn.secondary {
  background: var(--secondary);
  color: var(--secondary-foreground);
}

.btn.ghost {
  background: transparent;
  color: var(--foreground);
  border: 1px solid var(--border);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>